#include "manager.h"

#include "jsonutils.h"

#include <QFile>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDir>

Manager::Manager(QObject *parent)
    : QObject{parent}
{}

void Manager::saveJson(QString fileName, QString key, QString value)
{
    JsonUtils::saveJsonFile(fileName, key, value);
}

void Manager::loadJson()
{
    qDebug() << "1111111111";
    QDir jsonDir("../../loadJson");

    QFileInfoList files = jsonDir.entryInfoList(QDir::NoDotAndDotDot | QDir::Files);
    qDebug() << files.size();
    foreach (QFileInfo fileInfo, files) {
        QFile file(fileInfo.absoluteFilePath());
        if (!file.open(QIODevice::ReadWrite)) {
            qDebug() << "file not open :" << file.errorString();
            return;
        }
        QByteArray buf = file.readAll();


        QJsonDocument jsonDoc = QJsonDocument::fromJson(buf);
        if (jsonDoc.isNull()) {
            qDebug() << "无法解析json字符串";
            return;
        }
        if (!jsonDoc.isObject()) {
            qDebug() << "json file is not object";
            return;
        }

        QJsonObject jsonObject = jsonDoc.object();

        QString namePrefix = "button";
        int count = 0;
        while (count != -1) {
            QString key = namePrefix + QString::number(count);
            qDebug() << "key =" << key;
            QJsonValue jsonValue = jsonObject[key];

            if (jsonValue.isNull()) {
                break;
            }
            if (!jsonValue.isObject()) {
                break;
            }
            QString text = jsonValue.toObject().value("text").toString();
            QString cmd = jsonValue.toObject().value("cmd").toString();
            emit initDisplay(0, key, text, cmd);
            count++;
        }


    }
}
